﻿using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Serialization;
using ConfigurationManagement.Data;
using Environment = ConfigurationManagement.Data.Environment;

namespace ConfigurationManagement.Administration.UI.Import
{
    public partial class ImportXmlDictionaryForm : Form
    {
        private readonly ConfigurationManagementDataContext _db = new ConfigurationManagementDataContext();
        private Project _selectedProject;
        private Solution _selectedSolution;

        public ImportXmlDictionaryForm()
        {
            InitializeComponent();
        }

        private void BrowseButtonClick(object sender, EventArgs e)
        {
            var dr = openFileDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                DictionaryPathTextBox.Text = openFileDialog1.FileName;
            }
        }

        private void ImportXmlDictionaryFormLoad(object sender, EventArgs e)
        {
            LoadProjects();
        }

        private void LoadProjects()
        {
            ProjectsComboBox.DisplayMember = "ProjectName";
            ProjectsComboBox.ValueMember = "ProjectID";
            ProjectsComboBox.DataSource = _db.Projects;
            _selectedProject = (Project) ProjectsComboBox.SelectedItem;
            LoadSolutions();
        }

        private void LoadSolutions()
        {
            if (_selectedProject == null) return;
            SolutionsComboBox.DisplayMember = "SolutionName";
            SolutionsComboBox.ValueMember = "SolutionID";
            SolutionsComboBox.DataSource = _selectedProject.Solutions;
            _selectedSolution = (Solution) SolutionsComboBox.SelectedItem;
        }

        private void ProjectsComboBoxSelectedIndexChanged(object sender, EventArgs e)
        {
            if (ProjectsComboBox.SelectedIndex < 0) return;
            _selectedProject = (Project) ProjectsComboBox.SelectedItem;
            LoadSolutions();
        }

        private void ImportButtonClick(object sender, EventArgs e)
        {
            Configuration config;
            var serializer = new XmlSerializer(typeof (Configuration));
            using (var fs = File.Open(DictionaryPathTextBox.Text, FileMode.Open, FileAccess.Read))
            {
                config = (Configuration) serializer.Deserialize(fs);
            }
// ReSharper disable LoopCanBePartlyConvertedToQuery
            foreach (var group in config.SettingsGroup)
// ReSharper restore LoopCanBePartlyConvertedToQuery
            {
                foreach (var tag in group.Tag)
                {
                    SolutionSetting setting;

                    var tag1 = tag;
                    var count = _selectedSolution.SolutionSettings.Count(p => p.SettingTag == tag1.Key);
                    if (count > 0)
                    {
                        //Update
                        setting = _selectedSolution.SolutionSettings.Single(p => p.SettingTag == tag1.Key);
                        setting.DefaultValue = tag.DefaultValue;
                    }
                    else
                    {
                        //Add
                        setting = new SolutionSetting
                                      {
                                          DefaultValue = tag.DefaultValue,
                                          SettingDescription = string.Empty,
                                          SettingTag = tag.Key,
                                          SolutionID = _selectedSolution.SolutionID
                                      };
                    }

                    foreach (var environmentSetting in tag.Environment)
                    {
                        SettingValue settingVal;
                        Environment newEnvironment;

                        //Add environment
                        var setting1 = environmentSetting;
                        var environmentCount =
                            _selectedProject.Environments.Count(p => p.EnvironmentName == setting1.Name);
                        if (environmentCount == 0)
                        {
                            newEnvironment = new Environment
                                                 {
                                                     EnvironmentDEscription = string.Empty,
                                                     EnvironmentName = environmentSetting.Name,
                                                     ProjectID = _selectedProject.ProjectID
                                                 };
                            _selectedProject.Environments.Add(newEnvironment);
                        }
                        else
                        {
                            newEnvironment =
                                _selectedProject.Environments.Single(p => p.EnvironmentName == setting1.Name);
                        }


                        var settingValueCount =
                            setting.SettingValues.Count(p => p.Environment.EnvironmentName == setting1.Name);
                        if (settingValueCount == 0)
                        {
                            //Add
                            settingVal = new SettingValue
                                             {
                                                 SettingValue1 = environmentSetting.ConfigurationValue
                                             };
                            newEnvironment.SettingValues.Add(settingVal);
                            setting.SettingValues.Add(settingVal);
                        }
                        else
                        {
                            //Update
                            settingVal = setting.SettingValues.Single(p => p.Environment == newEnvironment);
                            settingVal.SettingValue1 = environmentSetting.ConfigurationValue;
                        }
                    }
                }
            }
            _db.SubmitChanges();
            MessageBox.Show(@"The data has been imported successfully");
        }

        private void SolutionsComboBoxSelectedIndexChanged(object sender, EventArgs e)
        {
            if (SolutionsComboBox.SelectedIndex >= 0)
            {
                _selectedSolution = (Solution) SolutionsComboBox.SelectedItem;
            }
        }
    }
}